package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"github.com/kataras/iris/v12"
)

func HspWorkCountList(ctx iris.Context) {
	page := ctx.URLParamInt64Default("page", 1)
	size := ctx.URLParamInt64Default("size", 20)
	if size > 50 {
		size = 20
	}
	keywords := ctx.URLParamDefault("keywords", "")
	groupby := ctx.URLParamDefault("groupby", "YYYY-MM")

	sidx := ctx.URLParamDefault("sidx", "WORK_COUNT")
	sord := ctx.URLParamDefault("sord", "desc")

	now := time.Now()
	y := now.Year()
	m := now.Month()
	date1def := time.Date(y, m, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
	date2def := time.Date(y, m+1, 1, 0, 0, 0, 0, time.Local).Add(-time.Hour * 24).Format("2006-01-02")

	date1 := ctx.URLParamDefault("date1", date1def)
	date2 := ctx.URLParamDefault("date2", date2def)

	listUrl := "https://www.hspcn.com/Hsp/DingDing/IndexWorkCount_List?"

	listUrl += fmt.Sprintf("&sidx=%s", sidx)
	listUrl += fmt.Sprintf("&sord=%s", sord)

	listUrl += fmt.Sprintf("&TIME_START=%s", date1)
	listUrl += fmt.Sprintf("&TIME_END=%s", date2)

	listUrl += fmt.Sprintf("&KEY_WORD=%s", keywords)
	listUrl += fmt.Sprintf("&GROUP_BY=%s", groupby)

	listUrl += fmt.Sprintf("&page=%d&rows=%d", page, size)
	listUrl += "&DEPTNAME=&_search=false"
	listUrl += fmt.Sprintf("&nd=%d", time.Now().UnixNano())

	req, err := http.NewRequest("GET", listUrl, nil)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if err != nil {
		log.Println(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": err.Error()})
		return
	}

	// 带上 cookie
	cookies := ctx.Request().Cookies()
	for _, ck := range cookies {
		req.AddCookie(ck)
	}
	req.Header.Add("Origin", "https://www.hspcn.com")
	req.Header.Add("Referer", "https://www.hspcn.com/Pub/DingDing/IndexWorkCount_List")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36 Edg/95.0.1020.30")

	log.Println("正在请求此接口：", req.URL.String())

	httpClient := &http.Client{}
	httpResp, err := httpClient.Do(req)
	if err != nil {
		log.Println(err.Error())
		ctx.JSON(iris.Map{"flag": false, "msg": err.Error()})
		return
	}
	defer httpResp.Body.Close()

	hspResponse, err := ioutil.ReadAll(httpResp.Body)

	// strResponse := string(hspResponse)

	var jsondata iris.Map
	json.Unmarshal(hspResponse, &jsondata)
	ctx.StopWithJSON(httpResp.StatusCode, jsondata)
}
